from tqsdk import TqApi, TqAuth, TqKq
import time

# 使用当前的账号和密码
api = TqApi(account=TqKq(), auth=TqAuth("cps168", "alibaba"))

# 要查询的合约代码
symbol = 'SHFE.ni2506'

# 获取持仓信息
# 先取消所有未成交委托单
for order in api.get_order().values():  # 修改此处：获取字典的值（订单对象）
    if order.status == "ALIVE":
        api.cancel_order(order)
api.wait_update()  # 等待取消操作完成

position = api.get_position(symbol)

# 输出持仓情况
print(f"合约 {symbol} 的持仓情况：")
print(f"空单数量: {position.pos_short}")
print(f"多单数量: {position.pos_long}")
print(f"当日空单数量: {position.pos_short_today}")
print(f"当日多单数量: {position.pos_long_today}")

# 询问用户是否平仓
print("请问是否平仓？请选择以下选项：")
print("1. 平空单")
print("2. 平多单")
print("3. 平当日空单")
print("4. 平当日多单")
print("输入 'No' 取消平仓")
choice = input("请输入你的选择: ")

# 定义不支持市价单的交易所列表
NON_MARKET_ORDER_EXCHANGES = ['CFFEX', 'SHFE', 'INE', 'SSE', 'SZSE']

# 解析合约代码获取交易所代码
exchange_id = symbol.split('.')[0]

if choice.lower() != 'no':
    try:
        choice_num = int(choice)
        limit_price = None
        # 获取行情数据以获取最新价
        quote = api.get_quote(symbol)
        if exchange_id in NON_MARKET_ORDER_EXCHANGES:
            # 对于不支持市价单的交易所，使用最新价作为限价
            api.wait_update()  # 等待行情更新
            limit_price = quote.last_price
            if limit_price is None:
                print("未获取到最新价格，无法下单")
                api.close()
                exit()

        if choice_num == 1 and position.pos_short > 0:
            order = api.insert_order(symbol=symbol, direction="BUY", offset="CLOSE", volume=position.pos_short, limit_price=limit_price)
        elif choice_num == 2 and position.pos_long > 0:
            order = api.insert_order(symbol=symbol, direction="SELL", offset="CLOSE", volume=position.pos_long, limit_price=limit_price)
        elif choice_num == 3 and position.pos_short_today > 0:
            order = api.insert_order(symbol=symbol, direction="BUY", offset="CLOSETODAY", volume=position.pos_short_today, limit_price=limit_price)
        elif choice_num == 4 and position.pos_long_today > 0:
            order = api.insert_order(symbol=symbol, direction="SELL", offset="CLOSETODAY", volume=position.pos_long_today, limit_price=limit_price)
        else:
            print("无效的选择或没有可平的仓位")
            api.close()
            exit()

        # 等待订单完成
        api.wait_update(deadline=time.time() + 1)
        if order.status == 'FINISHED':
            print("平仓成功")
        else:
            # 尝试输出失败原因
            error_msg = order.error_message if hasattr(order, 'error_message') else "未知原因"
            print(f"平仓失败，原因: {error_msg}")
    except ValueError:
        print("输入无效，请输入数字或 'No'")

# 关闭 API 连接
api.close()